<template>
  <div>
    <a-date-picker
      :value="momVal"
      :allowClear="allowClear"
      :disabled="disabled"
      :format="dateFormat"
      :mode="mode"
      :placeholder="placeholder"
      @change="dateChanged"
    >
    </a-date-picker>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  name: 'dateStringPicker',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    // 返回的日期格式
    dateFormat: {
      type: String,
      default: 'YYYY年MM月DD日'
    },
    // 类型,选择年份请传入"year",选择年月请传入"month"
    mode: {
      type: String,
      default: 'date'
    },
    placeholder: {
      type: String,
      default: '请选择日期'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    allowClear: {
      type: Boolean,
      default: true
    },
    // 判断输入的两种状态input/change
    triggerChange: {
      type: Boolean,
      default: true
    }
  },
  data () {
    const dateStr = this.value
    return {
      momVal: !dateStr ? null : moment(dateStr, this.dateFormat),
      lastValue: ''
    }
  },
  watch: {
    // value: {
    //   handler (val) {
    //     if (!val) {
    //       this.momVal = null
    //       console.log('监听到没有值')
    //     } else {
    //       this.momVal = moment(val, this.dateFormat)
    //       console.log('监听到有值')
    //     }
    //   },
    //   deep: true,
    //   immediate: true
    //
    // }
    value (val) {
      if (!val) {
        this.momVal = null
        console.log('监听到没有值')
      } else {
        this.momVal = moment(val, 'YYYYMMDD')
        console.log('监听到有值')
      }
    }
  },
  methods: {
    moment,
    dateChanged (mom) {
      console.log(mom)
      if (!mom) {
        if (this.triggerChange) {
          this.$emit('change', null)
        } else {
          this.$emit('input', null)
        }
      } else {
        console.log('有值')
        console.log(this.triggerChange)
        this.lastValue = moment(mom).format('YYYYMMDD')
        if (this.triggerChange) {
          this.$emit('change', this.lastValue)
          // this.momVal = mom
          console.log(this.lastValue)
          console.log(this.momVal)
        } else {
          this.$emit('input', this.lastValue)
          // this.momVal = mom
          console.log(this.lastValue)
        }
      }
    }
  }
}
</script>

<style scoped></style>
